package com.ruoyi.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.feign.ChatFeign;
import com.ruoyi.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.*;

@Service
public class ChatServiceImpl implements ChatService {

    @Resource
    private ChatFeign chatFeign;

    @Value("${ai.address}")
    private String aiAddress;

    @Value("${ai.your_api_key}")
    private String apiKey;

    @Value("${ai.chat_id}")
    private String chatId;

    @Autowired
    private RestTemplate restTemplate;

    private static final String QUICK_CHART_URL = "https://quickchart.io/chart";

    Map<String,String> Pacturetype = new HashMap<>();


    public ChatServiceImpl() {
        this.restTemplate = createRestTemplate();
        Pacturetype.put("统计","bar");
        Pacturetype.put("趋势","bar");
        Pacturetype.put("可视化","bar");
        Pacturetype.put("图表","bar");
        Pacturetype.put("条形图","bar");
        Pacturetype.put("折线图","line");
        Pacturetype.put("饼图","pie");
        Pacturetype.put("雷达图","radar");
        Pacturetype.put("散点图","scatter");
        Pacturetype.put("柱状图","bar");
    }

    // 配置支持二进制和JSON的转换器
    private RestTemplate createRestTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        // 添加二进制转换器
        restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter());
        // 添加JSON转换器（若需要调用/render端点）
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        return restTemplate;
    }


    private Map<String, Object> extractChartParams(Map<String,List<String>> paramsMap,String type) {
        // 使用传统方式初始化Map
        Map<String, Object> params = new HashMap<>();
        //params.put("type", "line");
        params.put("type", type);

        // 构建labels列表
        //List<String> labels = Arrays.asList("Q1", "Q2", "Q3", "Q4");
        List<String> labels = paramsMap.get("日期");

        // 构建dataset
        Map<String, Object> dataset = new HashMap<>();
        dataset.put("label", "销售额");
        //dataset.put("data", Arrays.asList(65, 59, 80, 81));
        dataset.put("data", paramsMap.get("气温"));

        // 构建data Map
        Map<String, Object> data = new HashMap<>();
        data.put("labels", labels);
        data.put("datasets", Collections.singletonList(dataset));

        params.put("data", data);
        System.out.println("参数:"+params);
        return params;
    }

    /*@Override
    public TableDataInfo sendCompletion(Map<String, Object> request) {
        // 强制关闭流式
        request.put("stream", false);

        String url = aiAddress + "/api/v1/chats/" + chatId + "/completions";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", apiKey);
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

        String body = response.getBody();
        TableDataInfo rspData = new TableDataInfo();

        try {
            // 判断是不是 JSON
            if (body != null && body.trim().startsWith("{")) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> resultMap = mapper.readValue(body, Map.class);
                rspData.setCode(HttpStatus.SUCCESS);
                rspData.setMsg("执行成功");
                rspData.setData(resultMap);
            } else {
                rspData.setCode(HttpStatus.ERROR);
                rspData.setMsg("AI服务返回格式异常: " + response.getHeaders().getContentType());
                rspData.setData(body);
            }
        } catch (Exception e) {
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("AI服务响应解析失败: " + e.getMessage());
            rspData.setData(body);
        }
        return rspData;
    }*/
    @Override
    public TableDataInfo sendCompletion(Map<String, Object> request) {
        request.put("stream", false);

        String url = aiAddress + "/api/v1/chats/" + chatId + "/completions";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", apiKey);
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);

        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

        String body = response.getBody();
        TableDataInfo rspData = new TableDataInfo();

        try {
            MediaType contentType = response.getHeaders().getContentType();
            // 判断是不是 SSE
            if (contentType != null && contentType.toString().contains("text/event-stream")) {
                // 解析 SSE，提取所有 data: 行
                String[] lines = body.split("\\r?\\n");
                String lastDataLine = null;
                for (String line : lines) {
                    if (line.startsWith("data:")) {
                        lastDataLine = line.substring(5).trim();
                    }
                }
                if (lastDataLine != null && lastDataLine.startsWith("{")) {
                    ObjectMapper mapper = new ObjectMapper();
                    Map<String, Object> resultMap = mapper.readValue(lastDataLine, Map.class);
                    rspData.setCode(HttpStatus.SUCCESS);
                    rspData.setMsg("执行成功");
                    rspData.setData(resultMap);
                } else {
                    rspData.setCode(HttpStatus.ERROR);
                    rspData.setMsg("AI服务返回SSE但内容无法解析为JSON");
                    rspData.setData(body);
                }
            } else if (body != null && body.trim().startsWith("{")) {
                // 普通 JSON
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> resultMap = mapper.readValue(body, Map.class);
                rspData.setCode(HttpStatus.SUCCESS);
                rspData.setMsg("执行成功");
                rspData.setData(resultMap);
            } else {
                rspData.setCode(HttpStatus.ERROR);
                rspData.setMsg("AI服务返回格式异常: " + contentType);
                rspData.setData(body);
            }
        } catch (Exception e) {
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("AI服务响应解析失败: " + e.getMessage());
            rspData.setData(body);
        }
        return rspData;
    }

    @Override
    public TableDataInfo createSession(Map<String, Object> requestBody) {
        Long userId = SecurityUtils.getUserId();
        requestBody.put("user_id", userId.toString());
        Map<String, Object> resultMap = chatFeign.createSession(chatId, apiKey, requestBody);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo updateSession(String sessionId, Map<String, Object> requestBody) {
        Long userId = SecurityUtils.getUserId();
        requestBody.put("user_id", userId.toString());
        Map<String, Object> resultMap = chatFeign.updateSession(chatId, apiKey, sessionId, requestBody);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo getSessions(Map<String, Object> requestBody) {

        Long userId = SecurityUtils.getUserId();

        Map<String, Object> resultMap = chatFeign.getSessions(chatId, apiKey, userId.toString());

        String require = Optional.ofNullable(requestBody.get("require")).map(String::valueOf).orElse("");
        if (require.equals("list")) { //调整出简化列表
            List<Map<String, Object>> simplifiedData = new ArrayList<>();
            Object dataObj = resultMap.get("data");
            if (dataObj instanceof List) {
                for (Map<String, Object> session : (List<Map<String, Object>>) dataObj) {
                    Map<String, Object> simplifiedSession = new HashMap<>();
                    simplifiedSession.put("id", session.get("id"));
                    simplifiedSession.put("name", session.get("name"));
                    simplifiedData.add(simplifiedSession);
                }
            }
            // 如果没有数据，也要返回空数组
            resultMap.put("data", simplifiedData);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo getSession(Map<String, Object> requestBody) {

        Assert.isTrue(requestBody.containsKey("sessionId"), "sessionId不能为空");
        Long userId = SecurityUtils.getUserId();

        Map<String, Object> resultMap = chatFeign.getSession(chatId, apiKey, requestBody.get("sessionId").toString(),userId.toString());

        String require = Optional.ofNullable(requestBody.get("require")).map(String::valueOf).orElse("");
        if (require.equals("list")) { //调整出简化列表
            List<Map<String, Object>> simplifiedData = new ArrayList<>();
            for (Map<String, Object> session : (List<Map<String, Object>>) resultMap.get("data")) {
                Map<String, Object> simplifiedSession = new HashMap<>();
                simplifiedSession.put("id", session.get("id"));
                simplifiedSession.put("name", session.get("name"));
                simplifiedData.add(simplifiedSession);
            }
            resultMap.put("data", simplifiedData);
        }
        for (Map<String, Object> session : (List<Map<String, Object>>) resultMap.get("data")) {
            for (Map message : ((List<Map<String,String>>) session.get("messages"))) {
                message.put("image", "");
                message.put("Mstype","text");
                if(message.get("content").toString().startsWith("|")){
                    Map<String, List<String>> stringListMap = DataPrecess.processData(message.get("content").toString());

                    Map<String, Object> chartParams = extractChartParams(stringListMap , "bar");
                    message.put("image", generateChartPac(chartParams));
                    message.put("Mstype","chart");
                    message.put("type","image");
                }
            }
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo deleteSessions(Map<String, Object> requestBody) {
        //将前端string数据类型转换成id列表
        String[] ids = requestBody.get("ids").toString().split(",");
        requestBody.put("ids", ids);
        Long userId = SecurityUtils.getUserId();
        requestBody.put("user_id", userId.toString());
        //删除session
        Map<String, Object> resultMap = chatFeign.deleteSessions(chatId, apiKey, requestBody);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("执行成功");
        rspData.setData(resultMap);
        return rspData;
    }

    @Override
    public TableDataInfo generateChart(Map<String, Object> chartConfig) {
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("chart", chartConfig);
            request.put("width", 600);
            request.put("height", 400);
            request.put("format", "png");
            request.put("backgroundColor", "transparent");

            ResponseEntity<byte[]> response = restTemplate.postForEntity(
                    QUICK_CHART_URL,
                    request,
                    byte[].class
            );

            if (response.getStatusCode() == org.springframework.http.HttpStatus.OK && response.hasBody()) {
                String base64Image = java.util.Base64.getEncoder().encodeToString(response.getBody());
                Map<String,String> resultMap  =  new HashMap<>();
                resultMap.put("imageData", base64Image);
                resultMap.put("Mstype","chart");
                resultMap.put("type","bot");
                return TableDataInfo.success("图表生成成功", resultMap);
            } else {
                return TableDataInfo.error("图表生成失败: 无效的API响应");
            }
        } catch (Exception e) {
            return TableDataInfo.error("图表生成失败: " + e.getMessage());
        }
    }


    public String generateChartPac(Map<String, Object> chartConfig) {
        try {
            Map<String, Object> request = new HashMap<>();
            request.put("chart", chartConfig);
            request.put("width", 600);
            request.put("height", 400);
            request.put("format", "png");
            request.put("backgroundColor", "transparent");

            ResponseEntity<byte[]> response = restTemplate.postForEntity(
                    QUICK_CHART_URL,
                    request,
                    byte[].class
            );

            if (response.getStatusCode() == org.springframework.http.HttpStatus.OK && response.hasBody()) {
                String base64Image = java.util.Base64.getEncoder().encodeToString(response.getBody());
                return base64Image;
            } else {
                return "图表生成失败: 无效的API响应";
            }
        } catch (Exception e) {
            return "图表生成失败: ";
        }
    }


}
